package com.cloud.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.mapper.UserMapper;
import com.cloud.pojo.User;
import com.cloud.service.UserService;
import com.cloud.vo.UpdatePsdvo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author haoyeee123
 * @since 2022-01-15
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     */
    @Override
    public User selectUser(User user) {
        String password = user.getPassword();
        byte[] bytes = password.getBytes();
        String md5Password = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Password);
        user = userMapper.selectUser(user);
        if (user == null) {
            return null;
        }
        return user;
    }

    /**
     * 用户注册
     */
    @Override
    public int addUser(User user) {
        String password = user.getPassword();
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(user.getUsername())) {
            return 0;
        }
        byte[] bytes = password.getBytes();
        String md5Password = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Password);
        user.setVip(0);
        return userMapper.insert(user);
    }

    /**
     * 用户更新密码
     */
    @Override
    public int updateUser(UpdatePsdvo params) {
        Integer uid = params.getUid();
        String oldPsd = DigestUtils.md5DigestAsHex(params.getOldPassword().getBytes());
        User user = userMapper.selectById(uid);
        if (!oldPsd.equals(user.getPassword())) {
            return 0;
        }
        String newPsd = DigestUtils.md5DigestAsHex(params.getNewPassword().getBytes());
        user.setPassword(newPsd);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("uid", uid);
        int update = userMapper.update(user, queryWrapper);
        return update;
    }

    /*
     * 开通VIP
     * */
    @Override
    public int addVIP(User user) {
        if (user.getVip() != null) {
            return 201;
        } else {
            user.setVip(1);
            int flag = userMapper.updateById(user);
            if (flag == 0) {
                return 200;
            }
        }
        return 201;
    }


}
